import Taro from '@tarojs/taro';

// 登录
export const login = (params: {username: string; password: string}) => {
  // 模拟登录
  const token = 'mock_token_' + Date.now();
  const user = {
    id: 1,
    username: params.username,
    nickname: params.username,
    avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
    bio: '这是一个示例简介',
    createdAt: new Date().toISOString()
  };
  
  // 保存到本地存储
  Taro.setStorageSync('token', token);
  Taro.setStorageSync('userInfo', user);
  
  return Promise.resolve({ token, user });
};

// 注册
export const register = (params: {username: string; password: string; nickname?: string}) => {
  // 模拟注册
  const token = 'mock_token_' + Date.now();
  const user = {
    id: 1,
    username: params.username,
    nickname: params.nickname || params.username,
    avatar: 'https://img.yzcdn.cn/vant/cat.jpeg',
    bio: '这是一个示例简介',
    createdAt: new Date().toISOString()
  };
  
  // 保存到本地存储
  Taro.setStorageSync('token', token);
  Taro.setStorageSync('userInfo', user);
  
  return Promise.resolve({ token, user });
};

// 获取当前用户信息
export const getCurrentUser = () => {
  const userInfo = Taro.getStorageSync('userInfo');
  if (!userInfo) {
    return Promise.reject(new Error('未登录'));
  }
  return Promise.resolve(userInfo);
};

// 更新用户信息
export const updateUserInfo = (data: any) => {
  const userInfo = Taro.getStorageSync('userInfo');
  if (!userInfo) {
    return Promise.reject(new Error('未登录'));
  }
  
  const newUserInfo = {
    ...userInfo,
    ...data
  };
  
  Taro.setStorageSync('userInfo', newUserInfo);
  return Promise.resolve(newUserInfo);
};

// 注销登录
export const logout = () => {
  Taro.removeStorageSync('token');
  Taro.removeStorageSync('userInfo');
  Taro.reLaunch({ url: '/pages/login/index' });
}; 